<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>认识平均分 - 课后练习</title>
    <style>
        * {
            box-sizing: border-box;
            font-family: "微软雅黑", sans-serif;
        }
        body {
            margin: 0;
            padding: 15px;
            background-color: #f0f8ff;
            color: #333;
            line-height: 1.5;
        }
        .container {
            max-width: 100%;
            margin: 0 auto;
            background-color: white;
            border-radius: 15px;
            padding: 15px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        h1 {
            text-align: center;
            color: #4a6baf;
            margin-bottom: 15px;
            font-size: 1.5rem;
        }
        .student-info {
            background-color: #e6f2ff;
            padding: 10px;
            border-radius: 10px;
            margin-bottom: 15px;
        }
        .student-info input {
            width: 100%;
            padding: 8px;
            margin: 5px 0;
            border: 1px solid #b3d9ff;
            border-radius: 5px;
        }
        .question {
            margin-bottom: 20px;
            padding: 12px;
            border-radius: 10px;
            background-color: #f9f9f9;
            border-left: 5px solid #4a6baf;
        }
        .question-title {
            font-weight: bold;
            margin-bottom: 10px;
            font-size: 1.1rem;
        }
        .options {
            margin: 10px 0;
        }
        .option {
            margin: 8px 0;
            padding: 10px;
            background-color: #e6f2ff;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        .option:hover {
            background-color: #d0e5ff;
        }
        .option.selected {
            background-color: #b3d9ff;
        }
        .operation-area {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            margin: 15px 0;
            padding: 12px;
            background-color: #f0f8ff;
            border-radius: 10px;
        }
        .items-container {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            width: 100%;
            justify-content: center;
            margin-bottom: 15px;
        }
        .item {
            width: 35px;
            height: 35px;
            background-color: #ffcc99;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
            font-size: 0.8rem;
        }
        .group {
            min-height: 100px;
            border: 2px dashed #aaa;
            border-radius: 10px;
            padding: 10px;
            flex: 1;
            min-width: 120px;
            display: flex;
            flex-wrap: wrap;
            gap: 6px;
            align-items: flex-start;
            align-content: flex-start;
        }
        .group-title {
            width: 100%;
            text-align: center;
            margin-bottom: 5px;
            font-weight: bold;
            font-size: 0.9rem;
        }
        .buttons {
            display: flex;
            justify-content: center;
            gap: 10px;
            margin: 20px 0;
            flex-wrap: wrap;
        }
        button {
            padding: 10px 15px;
            background-color: #4a6baf;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 1rem;
            transition: background-color 0.3s;
        }
        button:hover {
            background-color: #3a5a9f;
        }
        button:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }
        .result {
            margin-top: 20px;
            padding: 15px;
            background-color: #e6f7e9;
            border-radius: 10px;
            display: none;
        }
        .correct {
            color: #2e7d32;
            font-weight: bold;
        }
        .incorrect {
            color: #c62828;
            font-weight: bold;
        }
        .progress {
            display: flex;
            justify-content: center;
            margin-bottom: 15px;
            flex-wrap: wrap;
        }
        .progress-dot {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            background-color: #ddd;
            margin: 0 3px;
        }
        .progress-dot.active {
            background-color: #4a6baf;
        }
        .share-section {
            margin-top: 20px;
            padding: 15px;
            background-color: #fff9e6;
            border-radius: 10px;
            border: 1px solid #ffcc80;
            display: none;
        }
        .share-section h3 {
            margin-top: 0;
            color: #e65100;
        }
        #studentData {
            font-family: monospace;
            white-space: pre-wrap;
            background-color: #f5f5f5;
            padding: 10px;
            border-radius: 5px;
            max-height: 200px;
            overflow-y: auto;
            font-size: 0.9rem;
        }
        #copyBtn {
            background-color: #4caf50;
            margin-top: 10px;
        }
        #copyBtn:hover {
            background-color: #3d8b40;
        }
        .hint {
            font-size: 0.9rem;
            color: #666;
            margin-top: 5px;
        }
        @media (max-width: 480px) {
            .group {
                min-width: 100%;
                margin-bottom: 10px;
            }
            .operation-area {
                flex-direction: column;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>《认识平均分》课后练习</h1>
        
        <div class="student-info">
            <div>请输入您的信息：</div>
            <input type="text" id="studentName" placeholder="姓名">
            <input type="text" id="className" placeholder="班级">
        </div>
        
        <div class="progress">
            <div class="progress-dot active" id="dot1"></div>
            <div class="progress-dot" id="dot2"></div>
            <div class="progress-dot" id="dot3"></div>
            <div class="progress-dot" id="dot4"></div>
            <div class="progress-dot" id="dot5"></div>
            <div class="progress-dot" id="dot6"></div>
        </div>
        
        <div id="question1" class="question">
            <div class="question-title">1. 下面哪种分法是平均分？</div>
            <div class="options">
                <div class="option" data-value="A">A. 把6个苹果分成2份，一份1个，一份5个</div>
                <div class="option" data-value="B">B. 把6个苹果分成2份，每份3个</div>
                <div class="option" data-value="C">C. 把6个苹果分成3份，一份1个，一份2个，一份3个</div>
            </div>
        </div>
        
        <div id="question2" class="question" style="display:none">
            <div class="question-title">2. 有8个草莓，平均分给4个小朋友，每个小朋友分到几个草莓？</div>
            <div class="options">
                <div class="option" data-value="A">A. 2个</div>
                <div class="option" data-value="B">B. 3个</div>
                <div class="option" data-value="C">C. 4个</div>
            </div>
        </div>
        
        <div id="question3" class="question" style="display:none">
            <div class="question-title">3. 请把10个糖果平均分给2个小朋友</div>
            <div class="hint">提示：拖动糖果到小朋友的盒子里</div>
            <div class="operation-area">
                <div class="items-container">
                    <div class="item" data-id="1">糖</div>
                    <div class="item" data-id="2">糖</div>
                    <div class="item" data-id="3">糖</div>
                    <div class="item" data-id="4">糖</div>
                    <div class="item" data-id="5">糖</div>
                    <div class="item" data-id="6">糖</div>
                    <div class="item" data-id="7">糖</div>
                    <div class="item" data-id="8">糖</div>
                    <div class="item" data-id="9">糖</div>
                    <div class="item" data-id="10">糖</div>
                </div>
                <div class="group" id="group1">
                    <div class="group-title">小朋友1</div>
                </div>
                <div class="group" id="group2">
                    <div class="group-title">小朋友2</div>
                </div>
            </div>
            <div style="text-align: center; margin-top: 10px;">
                <button id="reset3">重新分配</button>
            </div>
        </div>
        
        <div id="question4" class="question" style="display:none">
            <div class="question-title">4. 判断：把12块饼干平均分成4份，每份一定是3块。</div>
            <div class="options">
                <div class="option" data-value="A">A. 正确</div>
                <div class="option" data-value="B">B. 错误</div>
            </div>
        </div>
        
        <div id="question5" class="question" style="display:none">
            <div class="question-title">5. 请把15个橘子平均分到3个盘子里</div>
            <div class="hint">提示：拖动橘子到盘子里</div>
            <div class="operation-area">
                <div class="items-container">
                    <div class="item" data-id="1">橘</div>
                    <div class="item" data-id="2">橘</div>
                    <div class="item" data-id="3">橘</div>
                    <div class="item" data-id="4">橘</div>
                    <div class="item" data-id="5">橘</div>
                    <div class="item" data-id="6">橘</div>
                    <div class="item" data-id="7">橘</div>
                    <div class="item" data-id="8">橘</div>
                    <div class="item" data-id="9">橘</div>
                    <div class="item" data-id="10">橘</div>
                    <div class="item" data-id="11">橘</div>
                    <div class="item" data-id="12">橘</div>
                    <div class="item" data-id="13">橘</div>
                    <div class="item" data-id="14">橘</div>
                    <div class="item" data-id="15">橘</div>
                </div>
                <div class="group" id="group3">
                    <div class="group-title">盘子1</div>
                </div>
                <div class="group" id="group4">
                    <div class="group-title">盘子2</div>
                </div>
                <div class="group" id="group5">
                    <div class="group-title">盘子3</div>
                </div>
            </div>
            <div style="text-align: center; margin-top: 10px;">
                <button id="reset5">重新分配</button>
            </div>
        </div>
        
        <div id="question6" class="question" style="display:none">
            <div class="question-title">6. 把16个气球平均分给4个小朋友，每个小朋友分到几个？</div>
            <div class="options">
                <div class="option" data-value="A">A. 3个</div>
                <div class="option" data-value="B">B. 4个</div>
                <div class="option" data-value="C">C. 5个</div>
            </div>
        </div>
        
        <div class="buttons">
            <button id="prevBtn" disabled>上一题</button>
            <button id="nextBtn">下一题</button>
            <button id="submitBtn" style="display:none">提交答案</button>
        </div>
        
        <div id="result" class="result"></div>
        
        <div id="shareSection" class="share-section">
            <h3>答题完成！请将以下代码发送给老师：</h3>
            <div id="studentData"></div>
            <button id="copyBtn">复制代码</button>
            <div class="hint">复制后可以通过微信、QQ等方式发送给老师</div>
        </div>
    </div>

    <script>
        // 学生数据记录
        const studentData = {
            startTime: new Date(),
            studentName: '',
            className: '',
            answers: {},
            operationProcess: {}
        };

        // 当前题目索引
        let currentQuestion = 1;
        const totalQuestions = 6;

        // 正确答案
        const correctAnswers = {
            1: "B",
            2: "A",
            3: "equal", // 特殊标记，需要检查是否平均分配
            4: "A",
            5: "equal", // 特殊标记，需要检查是否平均分配
            6: "B"
        };

        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 更新进度点
            updateProgressDots();
            
            // 学生信息输入
            document.getElementById('studentName').addEventListener('input', function() {
                studentData.studentName = this.value;
            });
            
            document.getElementById('className').addEventListener('input', function() {
                studentData.className = this.value;
            });
            
            // 选项点击事件
            document.querySelectorAll('.option').forEach(option => {
                option.addEventListener('click', function() {
                    // 清除同一问题中其他选项的选择状态
                    const parent = this.parentElement;
                    parent.querySelectorAll('.option').forEach(opt => {
                        opt.classList.remove('selected');
                    });
                    
                    // 设置当前选项为选中状态
                    this.classList.add('selected');
                    
                    // 记录答案
                    const questionNum = getCurrentQuestionNumber();
                    studentData.answers[questionNum] = this.getAttribute('data-value');
                    
                    // 检查是否可以自动进入下一题
                    if (questionNum !== 3 && questionNum !== 5) {
                        setTimeout(() => {
                            if (currentQuestion < totalQuestions) {
                                document.getElementById('nextBtn').click();
                            }
                        }, 800);
                    }
                });
            });
            
            // 上一题按钮
            document.getElementById('prevBtn').addEventListener('click', function() {
                if (currentQuestion > 1) {
                    currentQuestion--;
                    showQuestion(currentQuestion);
                    updateProgressDots();
                    updateButtons();
                }
            });
            
            // 下一题按钮
            document.getElementById('nextBtn').addEventListener('click', function() {
                if (currentQuestion < totalQuestions) {
                    currentQuestion++;
                    showQuestion(currentQuestion);
                    updateProgressDots();
                    updateButtons();
                }
            });
            
            // 提交按钮
            document.getElementById('submitBtn').addEventListener('click', function() {
                if (!studentData.studentName || !studentData.className) {
                    alert('请先填写姓名和班级！');
                    return;
                }
                calculateScore();
            });
            
            // 重置按钮
            document.getElementById('reset3').addEventListener('click', function() {
                resetOperation(3);
            });
            
            document.getElementById('reset5').addEventListener('click', function() {
                resetOperation(5);
            });
            
            // 复制按钮
            document.getElementById('copyBtn').addEventListener('click', function() {
                copyStudentData();
            });
            
            // 初始化操作题
            initOperationQuestions();
            
            // 尝试加载之前保存的进度
            loadProgress();
        });

        // 显示指定题目
        function showQuestion(num) {
            // 隐藏所有题目
            for (let i = 1; i <= totalQuestions; i++) {
                document.getElementById('question' + i).style.display = 'none';
            }
            
            // 显示当前题目
            document.getElementById('question' + num).style.display = 'block';
            
            // 保存进度
            saveProgress();
        }

        // 更新进度点
        function updateProgressDots() {
            for (let i = 1; i <= totalQuestions; i++) {
                const dot = document.getElementById('dot' + i);
                if (i === currentQuestion) {
                    dot.classList.add('active');
                } else {
                    dot.classList.remove('active');
                }
            }
        }

        // 更新按钮状态
        function updateButtons() {
            document.getElementById('prevBtn').disabled = currentQuestion === 1;
            
            if (currentQuestion === totalQuestions) {
                document.getElementById('nextBtn').style.display = 'none';
                document.getElementById('submitBtn').style.display = 'inline-block';
            } else {
                document.getElementById('nextBtn').style.display = 'inline-block';
                document.getElementById('submitBtn').style.display = 'none';
            }
            
            // 保存进度
            saveProgress();
        }

        // 获取当前题目编号
        function getCurrentQuestionNumber() {
            return currentQuestion;
        }

        // 初始化操作题
        function initOperationQuestions() {
            // 为所有可拖拽项目添加事件
            document.querySelectorAll('.item').forEach(item => {
                item.setAttribute('draggable', 'true');
                
                item.addEventListener('dragstart', function(e) {
                    e.dataTransfer.setData('text/plain', this.getAttribute('data-id'));
                });
                
                // 添加触摸事件支持
                item.addEventListener('touchstart', handleTouchStart, false);
                item.addEventListener('touchmove', handleTouchMove, false);
                item.addEventListener('touchend', handleTouchEnd, false);
            });
            
            // 为所有分组添加事件
            document.querySelectorAll('.group').forEach(group => {
                group.addEventListener('dragover', function(e) {
                    e.preventDefault();
                });
                
                group.addEventListener('drop', function(e) {
                    e.preventDefault();
                    const itemId = e.dataTransfer.getData('text/plain');
                    moveItemToGroup(itemId, this.id);
                });
                
                // 添加触摸事件支持
                group.addEventListener('touchmove', handleTouchMove, false);
                group.addEventListener('touchend', handleTouchEnd, false);
            });
            
            // 触摸事件相关变量
            let touchStartX, touchStartY;
            let draggedItem = null;
            
            function handleTouchStart(e) {
                const touch = e.touches[0];
                touchStartX = touch.clientX;
                touchStartY = touch.clientY;
                draggedItem = e.target;
                
                // 添加拖动效果
                draggedItem.style.opacity = '0.7';
            }
            
            function handleTouchMove(e) {
                if (!draggedItem) return;
                
                e.preventDefault();
                const touch = e.touches[0];
                
                // 移动元素
                draggedItem.style.position = 'relative';
                draggedItem.style.left = (touch.clientX - touchStartX) + 'px';
                draggedItem.style.top = (touch.clientY - touchStartY) + 'px';
            }
            
            function handleTouchEnd(e) {
                if (!draggedItem) return;
                
                // 重置样式
                draggedItem.style.opacity = '1';
                draggedItem.style.position = 'static';
                draggedItem.style.left = '0';
                draggedItem.style.top = '0';
                
                // 检查是否在分组区域内
                const touch = e.changedTouches[0];
                const elements = document.elementsFromPoint(touch.clientX, touch.clientY);
                
                for (let element of elements) {
                    if (element.classList.contains('group')) {
                        moveItemToGroup(draggedItem.getAttribute('data-id'), element.id);
                        break;
                    }
                }
                
                draggedItem = null;
            }
        }
        
        // 移动项目到分组
        function moveItemToGroup(itemId, groupId) {
            const draggedItem = document.querySelector(`.item[data-id="${itemId}"]`);
            const targetGroup = document.getElementById(groupId);
            
            if (draggedItem && draggedItem.parentElement !== targetGroup) {
                targetGroup.appendChild(draggedItem);
                
                // 记录操作过程
                const questionNum = getCurrentQuestionNumber();
                if (!studentData.operationProcess[questionNum]) {
                    studentData.operationProcess[questionNum] = [];
                }
                
                studentData.operationProcess[questionNum].push({
                    time: new Date(),
                    item: itemId,
                    from: draggedItem.parentElement.id,
                    to: targetGroup.id
                });
                
                // 保存进度
                saveProgress();
            }
        }

        // 重置操作题
        function resetOperation(questionNum) {
            const itemsContainer = document.querySelector(`#question${questionNum} .items-container`);
            const groups = document.querySelectorAll(`#question${questionNum} .group`);
            
            // 将所有项目移回原始容器
            groups.forEach(group => {
                while (group.children.length > 1) { // 保留标题
                    itemsContainer.appendChild(group.lastChild);
                }
            });
            
            // 清空该题的操作记录
            if (studentData.operationProcess[questionNum]) {
                studentData.operationProcess[questionNum] = [];
            }
            
            // 保存进度
            saveProgress();
        }

        // 计算分数
        function calculateScore() {
            let score = 0;
            let resultHTML = "<h3>答题结果</h3>";
            
            for (let i = 1; i <= totalQuestions; i++) {
                const userAnswer = studentData.answers[i];
                const correctAnswer = correctAnswers[i];
                
                let isCorrect = false;
                
                // 处理操作题
                if (i === 3 || i === 5) {
                    isCorrect = checkOperationAnswer(i);
                } else {
                    isCorrect = userAnswer === correctAnswer;
                }
                
                if (isCorrect) {
                    score++;
                    resultHTML += `<p>第${i}题: <span class="correct">正确</span></p>`;
                } else {
                    resultHTML += `<p>第${i}题: <span class="incorrect">错误</span>`;
                    
                    if (i === 3 || i === 5) {
                        resultHTML += ` (操作未平均分配)`;
                    } else {
                        resultHTML += ` (正确答案: ${correctAnswer})`;
                    }
                    
                    resultHTML += `</p>`;
                }
            }
            
            resultHTML += `<p><strong>总分: ${score}/${totalQuestions}</strong></p>`;
            
            document.getElementById('result').innerHTML = resultHTML;
            document.getElementById('result').style.display = 'block';
            
            // 记录完成时间
            studentData.endTime = new Date();
            studentData.score = score;
            studentData.completionTime = Math.round((studentData.endTime - studentData.startTime) / 1000);
            
            // 生成分享代码
            generateShareCode();
            
            // 清除保存的进度
            localStorage.removeItem('averageDivisionProgress');
        }

        // 检查操作题答案
        function checkOperationAnswer(questionNum) {
            let groups = [];
            
            if (questionNum === 3) {
                groups = [
                    document.getElementById('group1'),
                    document.getElementById('group2')
                ];
            } else if (questionNum === 5) {
                groups = [
                    document.getElementById('group3'),
                    document.getElementById('group4'),
                    document.getElementById('group5')
                ];
            }
            
            // 计算每组中的项目数
            const counts = groups.map(group => group.children.length - 1); // 减去标题
            
            // 检查是否所有组数量相等
            const firstCount = counts[0];
            return counts.every(count => count === firstCount) && 
                   counts.reduce((sum, count) => sum + count, 0) === (questionNum === 3 ? 10 : 15);
        }

        // 生成分享代码
        function generateShareCode() {
            // 创建简化的数据对象用于分享
            const shareData = {
                name: studentData.studentName,
                class: studentData.className,
                score: studentData.score,
                total: totalQuestions,
                time: studentData.completionTime,
                answers: studentData.answers,
                operations: {}
            };
            
            // 添加操作题结果
            for (let i = 3; i <= 5; i += 2) {
                if (studentData.operationProcess[i]) {
                    let groups = [];
                    
                    if (i === 3) {
                        groups = [
                            document.getElementById('group1'),
                            document.getElementById('group2')
                        ];
                    } else {
                        groups = [
                            document.getElementById('group3'),
                            document.getElementById('group4'),
                            document.getElementById('group5')
                        ];
                    }
                    
                    shareData.operations[i] = {
                        correct: checkOperationAnswer(i),
                        distribution: groups.map(group => group.children.length - 1)
                    };
                }
            }
            
            // 转换为JSON字符串并编码
            const jsonString = JSON.stringify(shareData);
            const encodedString = btoa(unescape(encodeURIComponent(jsonString)));
            
            // 显示分享区域
            document.getElementById('studentData').textContent = encodedString;
            document.getElementById('shareSection').style.display = 'block';
            
            // 滚动到分享区域
            document.getElementById('shareSection').scrollIntoView({ behavior: 'smooth' });
        }

        // 复制学生数据
        function copyStudentData() {
            const textarea = document.createElement('textarea');
            textarea.value = document.getElementById('studentData').textContent;
            document.body.appendChild(textarea);
            textarea.select();
            document.execCommand('copy');
            document.body.removeChild(textarea);
            
            alert('已复制到剪贴板！现在可以发送给老师了。');
        }

        // 保存进度到本地存储
        function saveProgress() {
            const progress = {
                currentQuestion: currentQuestion,
                studentData: studentData
            };
            
            localStorage.setItem('averageDivisionProgress', JSON.stringify(progress));
        }

        // 从本地存储加载进度
        function loadProgress() {
            const savedProgress = localStorage.getItem('averageDivisionProgress');
            
            if (savedProgress) {
                try {
                    const progress = JSON.parse(savedProgress);
                    currentQuestion = progress.currentQuestion;
                    
                    // 恢复学生数据
                    Object.assign(studentData, progress.studentData);
                    
                    // 恢复学生信息输入
                    document.getElementById('studentName').value = studentData.studentName || '';
                    document.getElementById('className').value = studentData.className || '';
                    
                    // 恢复选择题答案
                    for (let i = 1; i <= totalQuestions; i++) {
                        if (studentData.answers[i] && i !== 3 && i !== 5) {
                            const questionElement = document.getElementById(`question${i}`);
                            if (questionElement) {
                                const option = questionElement.querySelector(`.option[data-value="${studentData.answers[i]}"]`);
                                if (option) {
                                    option.classList.add('selected');
                                }
                            }
                        }
                    }
                    
                    // 显示当前题目
                    showQuestion(currentQuestion);
                    updateProgressDots();
                    updateButtons();
                    
                    // 恢复操作题状态需要更复杂的逻辑，这里简化处理
                    // 在实际应用中，可能需要保存和恢复每个项目的具体位置
                    
                } catch (e) {
                    console.error('加载进度失败:', e);
                }
            }
        }

        // 初始显示第一题
        showQuestion(1);
        updateButtons();
    </script>
</body>
</html>